var ddmenuitem = null;
var _baseURL = null;
var _previousURL = null;

function menuOpen() {
	menuClose();
	ddmenuitem = $(this);
	ddmenuitem.addClass("selected");
	ddmenuitem.find("ul").show();
}

function menuClose() {
	if (ddmenuitem) {
		ddmenuitem.find("ul").hide();
		ddmenuitem.removeClass("selected");
		ddmenuitem = null;
	}
}

function processLink() {
	return goLink($(this).attr("href"));
}

function goLink(url) {
	document.location.href = _baseURL + ((url) ? "#" + url : "");
	_previousURL = _baseURL + "#" + ((url) ? "#" + url : "");
	
	execRequest(url);
	return false;
}

function execRequest(url) {
	menuClose();
	$.blockUI({message: $("#loading"), css: {border: 'none'}});
	$.ajax({
		url: url,
		success: function (data) {
			$.unblockUI();
			$("#content").html(data);
			$("#content a").click(processLink);
		},
		error: function() {
			$.unblockUI();
		}
	});
}

$(document).ready(function() {	
	_previousURL = document.location.href;
	_baseURL = document.location.href.split("#").slice(0, 1).join('');

	url = document.location.href.split("#").slice(1).join('');
	if (url) execRequest(url);

	$.history.init(function(url) {
		if (_previousURL != _baseURL + ((url) ? "#" + url : "")) {
			goLink(url);
		}
	});
	
	$("#mainmenu>ul>li").mouseover(menuOpen);
	$("#mainmenu>ul>li").mouseout(menuClose);
	
	$("#page").click(menuClose);
	
	$("#mainmenu a").click(processLink);
});